@using DaoHang.Services
@using DaoHang.Models
@inject ILogService LogService
@inject IJSRuntime JSRuntime

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="bi bi-journal-text me-2"></i>系统日志
        </h5>
        <div>
            <button class="btn btn-primary btn-sm" @onclick="LoadLogsAsync">
                <i class="bi bi-arrow-clockwise me-1"></i>刷新日志
            </button>
            <button class="btn btn-danger btn-sm ms-2" @onclick="ClearLogs">
                <i class="bi bi-trash me-1"></i>清空日志
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="mb-3">
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">日志级别</label>
                    <select class="form-select" @bind="logLevel" @bind:after="LoadLogsAsync">
                        <option value="">全部级别</option>
                        <option value="Information">信息</option>
                        <option value="Warning">警告</option>
                        <option value="Error">错误</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">日志分类</label>
                    <select class="form-select" @bind="logCategory" @bind:after="LoadLogsAsync">
                        <option value="">全部分类</option>
                        @foreach (var category in logCategories)
                        {
                            <option value="@category">@category</option>
                        }
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">搜索内容</label>
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="输入搜索关键词..." 
                               @bind="searchText" @bind:event="oninput" />
                        <button class="btn btn-outline-primary" @onclick="LoadLogsAsync">
                            <i class="bi bi-search"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        @if (isLoadingLogs)
        {
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2">加载中...</p>
            </div>
        }
        else if (logs.Any())
        {
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th>级别</th>
                            <th>分类</th>
                            <th>用户</th>
                            <th>消息</th>
                            <th width="50">详情</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var log in logs)
                        {
                            <tr class="@GetLogLevelClass(log.Level)">
                                <td>@log.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")</td>
                                <td>
                                    <span class="badge @GetLogLevelBadgeClass(log.Level)">
                                        @GetLogLevelText(log.Level)
                                    </span>
                                </td>
                                <td>@log.Category</td>
                                <td>@(string.IsNullOrEmpty(log.Username) ? "-" : log.Username)</td>
                                <td>@log.Message</td>
                                <td>
                                    @if (!string.IsNullOrEmpty(log.Exception))
                                    {
                                        <button class="btn btn-sm btn-outline-secondary" 
                                                @onclick="() => ShowLogDetails(log)">
                                            <i class="bi bi-eye"></i>
                                        </button>
                                    }
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            <div class="d-flex justify-content-between align-items-center mt-3">
                <div>
                    <span class="text-muted">共 @totalLogs 条记录</span>
                </div>
                <div>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item @(currentPage <= 1 ? "disabled" : "")">
                                <button class="page-link" @onclick="PreviousPage">上一页</button>
                            </li>
                            @for (int i = startPage; i <= endPage; i++)
                            {
                                var pageNumber = i;
                                <li class="page-item @(pageNumber == currentPage ? "active" : "")">
                                    <button class="page-link" @onclick="() => GoToPage(pageNumber)">@pageNumber</button>
                                </li>
                            }
                            <li class="page-item @(currentPage >= totalPages ? "disabled" : "")">
                                <button class="page-link" @onclick="NextPage">下一页</button>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        }
        else
        {
            <div class="text-center py-4 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-2">暂无日志数据</p>
            </div>
        }
    </div>
</div>

<!-- 日志详情模态框 -->
<div class="modal fade" id="logDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">日志详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                @if (selectedLog != null)
                {
                    <div class="mb-3">
                        <div class="d-flex mb-2">
                            <div class="badge @GetLogLevelBadgeClass(selectedLog.Level) me-2">
                                @GetLogLevelText(selectedLog.Level)
                            </div>
                            <div class="text-muted">@selectedLog.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")</div>
                        </div>
                        <h5>@selectedLog.Message</h5>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">分类：</label>
                        <span>@selectedLog.Category</span>
                    </div>

                    @if (!string.IsNullOrEmpty(selectedLog.Username))
                    {
                        <div class="mb-3">
                            <label class="form-label fw-bold">用户：</label>
                            <span>@selectedLog.Username</span>
                        </div>
                    }

                    @if (!string.IsNullOrEmpty(selectedLog.Exception))
                    {
                        <div class="mb-3">
                            <label class="form-label fw-bold">异常详情：</label>
                            <pre class="bg-light p-3 rounded"><code>@selectedLog.Exception</code></pre>
                        </div>
                    }
                }
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

@code {
    /// <summary>
    /// 日志数据列表
    /// </summary>
    private List<LogEntry> logs = new List<LogEntry>();

    /// <summary>
    /// 所有日志分类列表
    /// </summary>
    private List<string> logCategories = new List<string>();

    /// <summary>
    /// 当前选择的日志详情
    /// </summary>
    private LogEntry? selectedLog;

    /// <summary>
    /// 是否正在加载日志
    /// </summary>
    private bool isLoadingLogs = true;

    /// <summary>
    /// 日志过滤条件 - 级别
    /// </summary>
    private string logLevel = "";

    /// <summary>
    /// 日志过滤条件 - 分类
    /// </summary>
    private string logCategory = "";

    /// <summary>
    /// 日志过滤条件 - 搜索文本
    /// </summary>
    private string searchText = "";

    /// <summary>
    /// 分页 - 当前页码
    /// </summary>
    private int currentPage = 1;

    /// <summary>
    /// 分页 - 每页数量
    /// </summary>
    private int pageSize = 20;

    /// <summary>
    /// 分页 - 总记录数
    /// </summary>
    private int totalLogs = 0;

    /// <summary>
    /// 分页 - 总页数
    /// </summary>
    private int totalPages => (int)Math.Ceiling(totalLogs / (double)pageSize);

    /// <summary>
    /// 分页导航 - 起始页码
    /// </summary>
    private int startPage => Math.Max(1, currentPage - 2);

    /// <summary>
    /// 分页导航 - 结束页码
    /// </summary>
    private int endPage => Math.Min(totalPages, startPage + 4);

    /// <summary>
    /// 组件初始化时加载数据
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await LoadLogCategoriesAsync();
        await LoadLogsAsync();
    }

    /// <summary>
    /// 组件初始化后的JavaScript交互
    /// </summary>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 初始化模态框 - 使用更稳定的方式
            await JSRuntime.InvokeVoidAsync("initializeModal", "logDetailModal");
        }
    }

    /// <summary>
    /// 加载日志分类列表
    /// </summary>
    private async Task LoadLogCategoriesAsync()
    {
        try
        {
            logCategories = await LogService.GetLogCategoriesAsync();
        }
        catch (Exception)
        {
            // 处理异常
            logCategories = new List<string>();
        }
    }

    /// <summary>
    /// 加载日志数据
    /// </summary>
    private async Task LoadLogsAsync()
    {
        isLoadingLogs = true;
        try
        {
            var result = await LogService.GetLogsAsync(
                level: logLevel,
                category: logCategory,
                searchText: searchText,
                page: currentPage,
                pageSize: pageSize
            );

            logs = result.Logs;
            totalLogs = result.TotalCount;
        }
        catch (Exception)
        {
            // 处理异常
            logs = new List<LogEntry>();
            totalLogs = 0;
        }
        finally
        {
            isLoadingLogs = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 清空日志
    /// </summary>
    private async Task ClearLogs()
    {
        bool confirmed = await JSRuntime.InvokeAsync<bool>("confirm", "确定要清空所有日志吗？此操作不可恢复！");
        if (confirmed)
        {
            try
            {
                await LogService.ClearLogsAsync();
                await LoadLogsAsync();
            }
            catch (Exception)
            {
                await JSRuntime.InvokeVoidAsync("alert", "清空日志失败，请重试");
            }
        }
    }

    /// <summary>
    /// 显示日志详情
    /// </summary>
    private async Task ShowLogDetails(LogEntry log)
    {
        selectedLog = log;
        StateHasChanged();
        await JSRuntime.InvokeVoidAsync("showModal", "logDetailModal");
    }

    /// <summary>
    /// 分页 - 前一页
    /// </summary>
    private async Task PreviousPage()
    {
        if (currentPage > 1)
        {
            currentPage--;
            await LoadLogsAsync();
        }
    }

    /// <summary>
    /// 分页 - 下一页
    /// </summary>
    private async Task NextPage()
    {
        if (currentPage < totalPages)
        {
            currentPage++;
            await LoadLogsAsync();
        }
    }

    /// <summary>
    /// 分页 - 跳转到指定页
    /// </summary>
    private async Task GoToPage(int page)
    {
        currentPage = page;
        await LoadLogsAsync();
    }

    /// <summary>
    /// 获取日志级别对应的CSS类
    /// </summary>
    private string GetLogLevelClass(string level)
    {
        return level switch
        {
            "Error" => "table-danger",
            "Warning" => "table-warning",
            _ => ""
        };
    }

    /// <summary>
    /// 获取日志级别对应的Badge CSS类
    /// </summary>
    private string GetLogLevelBadgeClass(string level)
    {
        return level switch
        {
            "Error" => "bg-danger",
            "Warning" => "bg-warning text-dark",
            "Information" => "bg-info text-dark",
            _ => "bg-secondary"
        };
    }

    /// <summary>
    /// 获取日志级别的显示文本
    /// </summary>
    private string GetLogLevelText(string level)
    {
        return level switch
        {
            "Error" => "错误",
            "Warning" => "警告",
            "Information" => "信息",
            _ => level
        };
    }
} 